/** Author: JTrapp@Google.com
* 10.10.2007
*/
/** Some static configuration.*/
var rootURL="http://laterrevueduciel.googlecode.com/svn/trunk/";  // Where does the app live
var numImages=427; //Number of images/kml files

/** Some global vars.*/
var today; //placemark Id for the day
var currentImageId=-1;  // placemark id of image loaded
var kmlPlacemark;  // store the last read kml placemark, because it is used in map
var map = ""; // placeholder for the map. Will be initiated on first map open.
var myIcon; //the icon used in them map
var description; 
var markers;  //cache for markers, where markers can be retrieved by the placemark id
    
/** Called when the gadged is loaded*/
function init() {
    today = getId();
    tabs.alignTabs("left", 10);
    tabs.addDynamicTab("<div class='tab' id='imageTab'>"+prefs.getMsg("imageTab")+"</div>", _IG_Callback(showImageCallback,getId()));
    if (GBrowserIsCompatible()) { // Add a map tab, only if maps are supported
        tabs.addDynamicTab("<div class='tab' id='mapTab'>"+prefs.getMsg("mapTab")+"</div>", showMapCallback); 
    } 
    //tabs.setSelectedTab(0); // No show first tab.
}

/** Calculate the image number by the number of days since the gadget went live. 
After all images have been shown, it will start with 0 again.. */
function getId() {
    var now = new Date();
    var startDay = new Date(2007,8,26);
    var dayLen = 1000*60*60*24; // Make my day.
    return Math.ceil((now.getTime()-startDay.getTime())/dayLen)%numImages;
}


/** Callback is called each time the image tab is selected.
To prevent from being called every time, the last index
is stored. The kml will only be loaded, if the placemark 
Id has changed.*/
function showImageCallback(tabId){
     if(currentImageId<0) { //Only initialize the html once
        _gel(tabId).innerHTML="<h1><div id=\"header\">Loading ... </div></h1>"
        + "<div class=\"content\" id=\"content\"></div>"
        + "<table width=\"100%\"><tr><td><div class=\"status\" id=\"status\"></div></td>"
        + "<td align=\"right\"><a href=\"http://www.goodplanet.org/\" target=\"_blank\">"
        + "<img src=\""+_IG_GetImageUrl(rootURL+"images/logo_goodplanet.jpg")+"\"" 
        + "border=\"0\" alt=\"Good Planet Logo\"></img></a></div></td></tr></table>";
        show(getId());
    } else {
        _IG_AdjustIFrameHeight(); //Tab has not changed but needs to bre resized    
    }
}

/** Callback is called each time the map tab is selected.
To prevent from being called every time, the last index
is stored. The kml will only be loaded, if the placemark 
Id has changed.*/
function showMapCallback(tabId){
    if (map=="") {  //Lazy initialization
        _gel(tabId).innerHTML="<h1><div id=\"mapHeader\"></div></h1>"
        + "<div class=\"map\" id=\"map\"></div><table width=\"100%\">"
        + "<table><tr><td><div class=\"status\" id=\"mapStatus\">"+prefs.getMsg("loadingMap")+"</div></td>"
        + "<td align=\"right\"><a href=\"http://www.goodplanet.org/\" target=\"_blank\">"
        + "<img src=\""+_IG_GetImageUrl(rootURL+"images/logo_goodplanet.jpg")+"\" border=\"0\" alt=\"Good Planet Logo\"></img></a></div></td>"
        + "</tr></table>";

        initMap();
    }
    showMap(currentImageId);
}


function showMap(placemarkId){
    _gel("mapStatus").innerHTML =prefs.getMsg("loadingMap");
    _gel("mapHeader").innerHTML =getChildNodeValue(kmlPlacemark, "name");  
    
    var marker=markers[placemarkId]; // Store the marker to prevent the marker being generated  several times.


    if (marker==null){
        var lat = getNodeValue(kmlPlacemark, "latitude");
        var lng = getNodeValue(kmlPlacemark, "longitude");
        var point = new GLatLng(lat, lng);
        var imageLink = getElement(kmlPlacemark, "imageLink");
        
        var info = "<img src=\""
            +_IG_GetImageUrl(imageLink.firstChild.nodeValue)
            +"\" width=\"100%\">";
        marker = createMarker(placemarkId, point, info);

        
        map.panTo(point); 
        
        var zoomlevel = map.getCurrentMapType().getMaximumResolution()-1;
        
        map.setZoom(6); // use a fixed zoom level...
        _gel("mapStatus").innerHTML = createEarthLink(placemarkId);
    } else { //Workaround for vanishing markers
        map.setCenter(marker.getPoint());
        map.panBy(new GSize(100, 100));
        _gel("mapStatus").innerHTML = createEarthLink(placemarkId);
    
    } 

//    var zoomLevel = G_HYBRID_MAP.getMaximumResolution(point);
//    zoomLevel=zoomLevel<11?zoomlevel:11;


    _IG_AdjustIFrameHeight();
}


/** Create the url for the kml snipplets.*/
function getURL(placemarkId){
    var lang=prefs.getMsg("lang");
    if(lang==""){
        lang="en"; // Default language
    }
    return rootURL+"pub/generdata/yab_"+lang+placemarkId+".kml"
}
/** Create the url for the complete kmz.*/
function getURLZ(){
    var lang=prefs.getMsg("lang");
    if(lang==""){
        lang="en"; // Default language
    }
    return rootURL+"pub/generdata/yab_"+lang+".kmz"
}
/** Show the image and description as provided in the kml.*/
function show(placemarkId) {
    if (placemarkId!=currentImageId) {
        currentImageId=placemarkId;
         _gel("status").innerHTML ="<a href=\""+getURL(placemarkId)+"\"/>"+prefs.getMsg("loadingImage")+"</a>";
        _IG_FetchXmlContent(getURL(placemarkId), function (response) {
        if (response == null || typeof(response) != "object" ||
        response.firstChild == null){
            _gel("header").innerHTML = "<a href=\"javascript:show("+placemarkId+")\"/>"+prefs.getMsg("errorRetry")+"</a>";
            _gel("content").innerHTML ="<a href=\""+getURL(placemarkId)+"\"/>"+getURL(placemarkId)+"</a>";
        } else {
            var document = response.getElementsByTagName("Document");
            var kmlDoc=document[0];
            var placemarks = kmlDoc.getElementsByTagName("Placemark");

            kmlPlacemark = placemarks[0];
            _IG_SetTitle(getChildNodeValue(kmlDoc,"name"));
            _IG_SetTitle(prefs.getMsg("title"));
            _gel("header").innerHTML =getChildNodeValue(kmlPlacemark, "name");
            description = getChildNodeValue(kmlPlacemark, "description");
            var prefString="";
            var nextString="";
            if (placemarkId > 0) {
                var prevId = placemarkId - 1;
                prefString ="<a href=\"javascript:show("+prevId
                    +")\"><img src=\""+_IG_GetImageUrl(rootURL
                    +"/images/arrow_left.jpg")+"\" width=\"14\" height=\"14\" alt=\""
                    +prefs.getMsg("previousTT")+"\" border=\"0\"/></a>"; 
            }
            if (placemarkId < today) {
                var nextId = placemarkId + 1;
                nextString="<a href=\"javascript:show("+nextId
                    +")\"><img src=\""+_IG_GetImageUrl(rootURL
                    +"/images/arrow_right.jpg")+"\" width=\"14\" height=\"14\" alt=\""
                    +prefs.getMsg("nextTT")+"\" border=\"0\"/></a>"; 
            }
            var imageLink = getElement(kmlPlacemark, "imageLink");
            var width = imageLink.getAttribute("width");

            var content = _gel("content");
            var contentWidth = content.offsetWidth;
            var height = imageLink.getAttribute("height") * contentWidth / width;
            
            content.innerHTML = 
                "<img src=\""+_IG_GetImageUrl(imageLink.firstChild.nodeValue)
                + "\" width=\""+contentWidth
                + "\" height=\""+height
                + "\"><table width=\"100%\"<tr><td width=\"10%\" >"
                +prefString+"</td><td align=\"center\" class=\"copyright\"><a target=\"_blank\" href=\"http://www.yannarthusbertrand.com/\"> &copy; Yann Arthus-Bertrand </a></td><td align=\"right\" width=\"10%\">"
                +nextString+"</td></tr></table>"
                +description;            

        }  
        _gel("status").innerHTML = createEarthLink(placemarkId);
        _IG_AdjustIFrameHeight();    }, { refreshInterval: 0 }); // TODO: remove refreshInterval for production
     } else {
        _IG_AdjustIFrameHeight();  
    }
} 

/**
 * Retrieve the first child element found for a given tag starting from an element.
 * Since behaviour is different for ie and firefox, use only when the tagname is 
 * unique. Use getChildNodeValue instead to make sure, you get the direct child.s
 * This method will only look for direct childs. No grandchilds will be found.
 * For some an unknown reason, I didn't get the standard getElementsByTagNameNS 
 * to work. If you know how, please substitute and let me know.
 * This function should not be use for prefixed nodes. Use getNodeNS instead.
 *
 * @param {Element} element Some Dom element
 * @param {String} tagname The child elements tag name.
 * @return {Node}Child element or the String "[<"+tagname+"> null]" or "[<"+tagname+"> not found]". 
 */
  
  function getNodeValue(element, tagname) {
    var nodeList = element.getElementsByTagName(tagname);
    if (nodeList.length>0) {
        if (nodeList.item(0).firstChild!=null) {
                return nodeList.item(0).firstChild.nodeValue;
        } else {
                return "[<"+tagname+"> null]";
        }
    }
    return "[<"+tagname+"> not found]";
}
/**
 * Retrieve the first child element for a given tag.
 * this method will only look for direct childs. No grandchilds will be found.
 * For some an unknown reason, I didn't get the standard getElementsByTagNameNS 
 * to work. If you know how, please substitute and let me know.
  
 * @param {Element} element Some Dom element
 * @param {String} tagname The child elements tag name, which may include the namespace prefix.
 * @return {Node}Child element or the String "[<"+tagname+"> null]" or "[<"+tagname+"> not found]". 
 */
 function getChildNodeValue(element, tagname) {
     var nodeList = element.childNodes;
    for (var i = 0, node; node = nodeList[i]; i++) {
        if (node.nodeName == tagname){
           if (node.firstChild!=null){
                   return node.firstChild.nodeValue;
            }
            else {
                    //alert("Empty node: "+node.nodeName);
                    return "";
            }
        }
     }
    return null;
}
/**
 * Retrieve the first child element for a given tag.
 * this method will only look for direct childs. No grandchilds will be found.
 * For some an unknown reason, I didn't get the standard getElementsByTagNameNS 
 * to work. If you know how, please substitute and let me know.
  
 * @param {Element} element Some Dom element
 * @param {String} tagname The child elements tag name, which may include the namespace prefix.
 * @return {Node}Child element or the String "[<"+tagname+"> null]" or "[<"+tagname+"> not found]". 
 */
 function getElement(element, tagname) {
     var nodeList = element.getElementsByTagName(tagname);
     return nodeList.item(0);    
    return null;
}

/** 
  * Check if Google earth is installed by checking the known
  * mimetypes (Netscape only).
  * @param {int} placemarkId The placemark id (position of the placemark)
 */
function createEarthLink(placemarkId) {
    if (navigator.mimeTypes && navigator.mimeTypes.length) { 
       if (navigator.mimeTypes['application/vnd.google-earth.kmz']) { //
           return "<a rel=\"alternate\" type=\"application/vnd.google-earth.kmz .kmz\" href=\""+getURLZ()+"#yab"+placemarkId
           +";balloonFlyto;\"/><img src=\""+_IG_GetImageUrl(rootURL+"images/button_"+prefs.getMsg(lang)+".jpg")
           +"\" border=\"0\" alt=\"" +prefs.getMsg("showInEarth")+"\"/></a>"; 
       }else{
           return "<a target=\"_blank\" href=\""+prefs.getMsg("earthLink")
                +"\">"+prefs.getMsg("installEarth")+"</a>";     
       } 
    } 
    else {  // iE TODO: detect installation of earth
        return "test "+ WM_test('GoogleEarth.IApplicationGE'); 
    } 
}
/** 
  * Check if Google earth is installed by checking the known
  * mimetypes (Netscape only).
  * @param {int} placemarkId The placemark id (position of the placemark)
 */
function createEarthLinktest(placemarkId) {
       if ( WM_pluginDetect('GoogleEarth', 'kmz', 'application/vnd.google-earth.kmz', 'GoogleEarth.checkKmlAssociations')) { //
           return "<a rel=\"alternate\" type=\"application/vnd.google-earth.kmz .kmz\" href=\""+getURLZ()+"#yab"+placemarkId
           +";balloonFlyto;\"/><img src=\""+_IG_GetImageUrl(rootURL+"images/view_on_google_earth_button_with_icon.jpg")
           +"\" border=\"0\" alt=\"" +prefs.getMsg("showInEarth")+"\"/></a>"; 
       }else{
           return "<a target=\"_blank\" href=\""+prefs.getMsg("earthLink")
                +"\">"+prefs.getMsg("installEarth")+"</a>";     
       } 
   
}

/** 
* Init the map vars. This is called the first time the 
* map tab is opened.
*/
function initMap() {
    map = new GMap2(_gel("map"));
    map.setCenter(new GLatLng(41.875696,-87.624207), 3); 
    map.addControl(new GSmallMapControl());
    if (prefs.getBool("showMapTypeControls")) { 
        map.addControl(new GMapTypeControl());
    }
    map.setMapType(G_HYBRID_MAP);

    myIcon = new GIcon();
    myIcon.iconSize = new GSize(42,42);
    myIcon.iconAnchor = new GPoint(42,42);
    myIcon.infoWindowAnchor = myIcon.iconAnchor;
    myIcon.image = _IG_GetImageUrl(rootURL+"/images/coeur64.png");

    markers = new Object();    
}


/**
 * Get a marker from the marker cache or create it for the current id and
 * the given point. 
 * @param {GLatLng} point Point in lat and long
 * @return {GMarker} gmarker
 */
function createMarker(placemarkId, point, info) {

        var marker = new GMarker(point, {icon:myIcon});
        markers[placemarkId] = marker;
        GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml(info, {maxWidth : 200});
           // _gel("imageDiv").innerHTML = "<img src=\""+_IG_GetImageUrl(getNodeValue(kmlPlacemark, "imageLink"))+"\" width=\"100%\">";            
        });
        map.addOverlay(marker);
 

    return marker;
}

